var express = require('express')
var fs = require('fs')
var path = require('path')
var bodyParser = require('body-parser')
var session = require('express-session')
var router = require('./router/router.js')
var jwt = require('jsonwebtoken')
var cors = require('cors')

var app = new express()

// app.use(cors())


// 设置跨域访问,开启 cors 跨域请求
app.all('/api/*', function (req, res, next) {
  res.header('Access-Control-Allow-Origin', '*')
  res.header('Access-Control-Allow-Headers', 'X-Requested-With, mytoken')
  res.header('Access-Control-Allow-Headers', 'X-Requested-With, Authorization')
  res.setHeader('Content-Type', 'application/json;charset=utf-8')
  res.header('Access-Control-Allow-Headers', 'Content-Type,Content-Length, Authorization, Accept,X-Requested-With')
  res.header('Access-Control-Allow-Methods', 'PUT,POST,GET,DELETE,OPTIONS')
  res.header('X-Powered-By', ' 3.2.1')
  if (req.method == 'OPTIONS')
    res.sendStatus(200)
  // 让options请求快速返回 
  else next()
})


// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({
  extended: false
}))
// parse application/json
app.use(bodyParser.json())

app.use(function (req, res, next) {
  let token = req.headers.authorization;
  if (!token) {
    jwt.verify(token, 'secret', (err, decoded) => {
      if (err) {
        switch (err.name) {
          case 'JsonWebTokenError':
            res.status(403).send({
              code: -1,
              msg: '无效的token'
            });
            break;
          case 'TokenExpiredError':
            res.status(403).send({
              code: -1,
              msg: 'token过期'
            });
            break;
        }
      }
      console.log('error')
    })
    return
  }
  next()
})


app.use(router)

app.listen(5000, function () {
  console.log('Listen port 5000')
})